package Network;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import Controler.Controler;
import Model.PropertiesUtils;

public class Server extends Thread {
	private Object parent = null;
	  private ObjectOutputStream oos;
	  private ObjectInputStream ios;
	  private ServerSocket socketserver  ;
	  private Socket socket;
	  private int port;
	  
	  
	  public Server(Object parent, int port) {
		  this.parent = parent;
		  this.port = port;
	  }

	public void run() {
		try {
			socketserver = new ServerSocket(port);

			socket = socketserver.accept();
			if(parent instanceof Controler){
				((Controler)parent).changeMessage(PropertiesUtils.informationsProperties("launchServer"));
			}
			ios = new ObjectInputStream(socket.getInputStream());
			oos = new ObjectOutputStream(socket.getOutputStream());
			while (!socket.isConnected());
			
			// If we wanna send something during the init.
			/*
			 * for(FormDrawable drawable : refPane.getDrawables()) {
			 * oos.flush(); oos.reset(); oos.writeObject(drawable); }
			 */
			if(parent instanceof Controler){
				((Controler)parent).hostReceivedClient();
			}
			while (socket.isConnected()) {
				// The object = ios.readObject();
				// Update Local Data from received object.
				Object rcvObj = ios.readObject();
				if(parent!=null)
					if(parent instanceof Controler)
						((Controler) parent).receive(rcvObj);
			}
			ios.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
	
	public void send(Object object)
	  {
        	try {
        		oos.flush();
        		oos.reset();
        		oos.writeObject(object);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	  }
}

